//
//  DDViewController.m
//  HeadYang
//
//  Created by sunmingming on 15/7/23.
//  Copyright (c) 2015年 xiaoluoli. All rights reserved.
//

#import "DDViewController.h"
#import "BarberAlertView.h"
#import "PayFInishView.h"
#import "CouponViewController.h"
#import "JianFaViewController.h"
#import "KGModal.h"
#import "Pingpp.h"

@interface DDViewController ()<UITableViewDataSource,UITableViewDelegate,PayFInishViewDelegate,PayDelegate>
@property(nonatomic,weak) IBOutlet UITableView *listView;
@property(nonatomic,strong) NSDictionary *chargeDic;
@property(nonatomic,assign) BOOL successPayed;

@end

@implementation DDViewController

@synthesize listView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = [tooles replaceNullFromDic:APPALL.barberDetailDic withKeyArray:@[@"name"]];
        APPALL.couponDic = nil;
        APPALL.ddVC = self;
        self.successPayed = NO;
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
    }
    return self;
}

-(void)dealloc{
    if(APPALL.orderDetailDic){
        if(!self.successPayed){
            NSDictionary *para =
            @{@"id":[APPALL.orderDetailDic valueForKey:@"id"],
              @"memo":@"",
              @"token":APPALL.myUserItem.token};
            [AVCloud callFunctionInBackground:@"order_cancel" withParameters:para block:^(id object, NSError *error) {
                // 执行结果
                if (!error && object) {
                } else {
                }
            }];
        }
    }
}

-(void)backPressed:(id)sender
{
    if(!APPALL.orderDetailDic)
        return;
    NSDictionary *para =
    @{@"id":[APPALL.orderDetailDic valueForKey:@"id"],
      @"memo":@"",
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_cancel" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                }
                    break;
                case 1:
                {
                    APPALL.orderDetailDic = nil;
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(APPALL.orderDetailDic){
        [self regetOrderDetail];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if(!APPALL.orderDetailDic)
        return 0;
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 2;
        case 1:
            return (APPALL.myType == hairJianFa)?1:2;
        case 2:
            return (APPALL.myType == hairJianFa)?2:3;
        case 3:
            return 1;
        case 4:
            return 2;
        case 5:
            return 1;
        default:
            return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger sectionI = indexPath.section;
    switch (sectionI) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    return 100.0f;
                case 1:
                    return 40.0f;
                default:
                    return 0;
            }
        case 1:
            switch (indexPath.row) {
                case 0:
                    return 44.0f;
                case 1:
                    return 44.0f;
                case 2:
                    return 44.0f;
                default:
                    return 0;
            }
        case 2:
            switch (indexPath.row) {
                case 0:
                    return 50.0f;
                case 1:
                    return 40.0f;
                case 2:
                    return 40.0f;
                case 3:
                    return 40.0f;
                default:
                    return 0.0f;
            }
        case 3:
            return 50.0f;
        case 4:
            switch (indexPath.row) {
                case 0:
                    return 50.0f;
                case 1:
                    return 60.0f;
                case 2:
                    return 60.0f;
                case 3:
                    return 60.0f;
                default:
                    return 0.0f;
            }
        case 5:
            return 60.0f;
        default:
            return 0;
    }
    return 0;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    NSInteger sectionI = indexPath.section;
    switch (sectionI) {
        case 0:
            switch (indexPath.row) {
                case 0:{
                    inde = @"DDHeadID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDHeadCell" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    UIImageView *img99 = (UIImageView*)[cell viewWithTag:99];
                    lab1.text = [tooles replaceNullFromDic:APPALL.orderDetailDic withKeyArray:@[@"barber"]];
                    lab2.text = [tooles replaceNullFromDic:APPALL.orderDetailDic withKeyArray:@[@"store"]];
                }
                    break;
                case 1:{
                    inde = @"DDHeadDetailID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDHeadDetail" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    lab1.text = [NSString stringWithFormat:@"预约时间\n%@",[[APPALL.orderDetailDic valueForKey:@"scheduleDate"] substringToIndex:10]];
                    lab2.text = [NSString stringWithFormat:@"%@-%@",[tooles replaceNullFromDic:APPALL.orderDetailDic withKeyArray:@[@"gender"]],[tooles replaceNullFromDic:APPALL.orderDetailDic withKeyArray:@[@"hairType"]]];
                }
                    break;
                default:
                    break;
            }
            break;
        case 1:{
            inde = @"DDTypeID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDType" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
            switch (indexPath.row) {
                case 0:
                    lab1.text = @"服务类型";
                {
                    switch (APPALL.myType) {
                        case hairJianFa:
                            lab2.text = @"剪发";
                            break;
                        case hairTangFa:
                            lab2.text = @"烫发";
                            break;
                        case hairRanFa:
                            lab2.text = @"染发";
                            break;
                        case hairHuli:
                            lab2.text = @"护理";
                            break;
                        default:
                            break;
                    }
                }
                    break;
                case 1:{
                    lab1.text = @"产品套餐";
                    lab2.text = [NSString stringWithFormat:@"%@%@",[tooles replaceNullFromDic:APPALL.goodsDic withKeyArray:@[@"brand"]],[tooles replaceNullFromDic:APPALL.goodsDic withKeyArray:@[@"name"]]];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 2:{
            int rowI = indexPath.row;
            if(rowI >= 1)
                rowI += (APPALL.myType == hairJianFa)?1:0;
            switch (rowI) {
                case 0:{
                    inde = @"DDPriceTitleID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDPriceTItle" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    float sumPrice = [[APPALL.goodsDic valueForKey:@"price"] floatValue] + APPALL.servicePrice;
                    lab2.text = [NSString stringWithFormat:@"￥%.2f",sumPrice];
                }
                    break;
                default:{
                    inde = @"DDPriceDetailID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDPriceDetail" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    if(rowI == 1){
                        lab1.textColor = [UIColor blackColor];
                        lab2.textColor = [UIColor darkGrayColor];
                        lab1.text = [NSString stringWithFormat:@"%@%@",[tooles replaceNullFromDic:APPALL.goodsDic withKeyArray:@[@"brand"]],[tooles replaceNullFromDic:APPALL.goodsDic withKeyArray:@[@"name"]]];
                        lab2.text = [NSString stringWithFormat:@"￥%.2f",[[APPALL.goodsDic valueForKey:@"price"] floatValue]];
                    }else if (rowI == 2){
                        lab1.textColor = [UIColor blackColor];
                        lab2.textColor = [UIColor darkGrayColor];
                        lab1.text = @"服务费用";
                        lab2.text = [NSString stringWithFormat:@"￥%.2f",APPALL.servicePrice];
                    }
                }
                    break;
            }
        }
            break;
        case 3:{
            inde = @"DDPriceTitleID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDPriceTItle" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
            UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
            lab1.text = @"使用优惠券";
            if(APPALL.couponDic){
                lab2.text = [NSString stringWithFormat:@"-￥%.2f",[[APPALL.couponDic valueForKey:@"price"] floatValue]];
            }else{
                lab2.text = @"未选择优惠券";
            }
        }
            break;
        case 4:{
            switch (indexPath.row) {
                case 0:{
                    inde = @"DDPriceTitleID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDPriceTItle" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    lab1.text = @"支付方式";
                    float sumPrice = [[APPALL.orderDetailDic valueForKey:@"dealPrice"] floatValue];
                    lab2.text = [NSString stringWithFormat:@"￥%.2f",sumPrice];
                }
                    break;
                default:{
                    inde = @"DDPayID";
                    cell = [tableView dequeueReusableCellWithIdentifier:inde];
                    if (cell == nil) {
                        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDPay" owner:self options:nil];
                        cell = [nib objectAtIndex:0];
                    }
                    UIImageView *icon1 = (UIImageView*)[cell viewWithTag:99];
                    UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
                    UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
                    
                    if(indexPath.row == 3){
                        icon1.image = [UIImage imageNamed:@"pay_icon_weixin.png"];
                        lab1.text = @"微信支付";
                        lab2.text = @"推荐已安装微信客户端的用户使用";
                    }else if (indexPath.row == 2){
                        icon1.image = [UIImage imageNamed:@"pay_icon_qq.png"];
                        lab1.text = @"QQ钱包支付";
                        lab2.text = @"推荐已安装QQ手机客户端的用户使用";
                    }else if (indexPath.row == 1){
                        icon1.image = [UIImage imageNamed:@"pay_icon_zhifubao.png"];
                        lab1.text = @"支付宝客户端支付";
                        lab2.text = @"推荐已安装支付宝客户端的用户使用";
                    }
                }
                    break;
            }
        }
            break;
        case 5:{
            inde = @"DDButtonID";
            cell = [tableView dequeueReusableCellWithIdentifier:inde];
            if (cell == nil) {
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DDButton" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            UIButton *but = (UIButton*)[cell viewWithTag:1];
            [but addTarget:self action:@selector(ddPressed:) forControlEvents:UIControlEventTouchUpInside];
        }
            break;
        default:
            break;
    }
    return cell;
}

-(void)ddPressed:(id)sender{
    [self getPayInfo];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 3){
        CouponViewController *vc = [CouponViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    if(indexPath.section == 4){
        return;
    }
    if(indexPath.section == 5){
        return;
    }
}

-(void)showAlertOfSuccess{
    self.successPayed = YES;
    NSLog(@"orderID:%@",[APPALL.orderDetailDic valueForKey:@"id"]);
    NSDictionary *para =
    @{@"order":[APPALL.orderDetailDic valueForKey:@"id"],
      @"type":@"pay",
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_wh_deal" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    [[KGModal sharedInstance] hideAnimated:NO];
                    PayFInishView *v = [PayFInishView new];
                    v.myDelegate = self;
                    [[KGModal sharedInstance] showWithContentView:v andAnimated:NO];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

-(void)payCancelPressed:(id)sender
{
    [[KGModal sharedInstance] hideAnimated:NO];
    APPALL.orderDetailDic = nil;
    [self.navigationController popToRootViewControllerAnimated:YES];
}

-(void)regetOrderDetail{
    NSDictionary *para =
    @{@"id":[APPALL.orderDetailDic valueForKey:@"id"],
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_index" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    APPALL.orderDetailDic = [aSucData objectForKey:@"order"];
                    [self.listView reloadData];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}


-(void)getPayInfo{
    NSDictionary *para =
    @{@"id":[APPALL.orderDetailDic valueForKey:@"id"],
      @"memo":@"",
      @"token":APPALL.myUserItem.token};
    [SVProgressHUD showWithStatus:@"loading..."];
    [AVCloud callFunctionInBackground:@"order_pay" withParameters:para block:^(id object, NSError *error) {
        // 执行结果
        if (!error && object) {
            NSLog(@"avget:%@",object);
            NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
            switch ([[aSucData valueForKey:@"success"] intValue]) {
                case 0:
                {
                    [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                }
                    break;
                case 1:
                {
                    self.chargeDic = [aSucData objectForKey:@"charge"];
                    float amount = [[APPALL.orderDetailDic valueForKey:@"dealPrice"] floatValue];
                    if (amount <= 0) {
                        return;
                    }
                    [Pingpp createPayment:self.chargeDic viewController:self appURLScheme:kUrlScheme withCompletion:^(NSString *result, PingppError *error) {
                        NSLog(@"ddview result:%@",result);
                        if (error == nil) {
                            if([result isEqualToString:@"success"]){
                                [self showAlertOfSuccess];
                            }else if([result isEqualToString:@"fail"]){
                                [SVProgressHUD showErrorWithStatus:@"付款失败"];
                            }else if([result isEqualToString:@"cancel"]){
                                [SVProgressHUD showErrorWithStatus:@"用户取消付款"];
                            }else if([result isEqualToString:@"invalid"]){
                            }
                        } else {
                            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"result=%@ PingppError: code=%lu msg=%@", result, (unsigned long)error.code, [error getMsg]]];
                        }
                        return;
                    }];
                }
                    break;
                default:
                    break;
            }
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

@end